<template>
  <div class="practice-container">
    <div class="practice-header">
      <div class="info">
        <span>难度：{{ difficulty }}</span>
        <span>进度：{{ currentIndex + 1 }}/{{ questions.length }}</span>
        <span>用时：{{ formatTime(timer) }}</span>
      </div>
    </div>

    <div class="question-container" v-if="currentQuestion">
      <div class="question">
        <h2>{{ currentQuestion.question }}</h2>
      </div>
      <div class="answer-input">
        <el-input
          v-model.number="userAnswer"
          type="number"
          placeholder="请输入答案"
          @keyup.enter.native="handleAnswer"
          :disabled="answered"
          ref="answerInput"
        >
        </el-input>
        <el-button
          type="primary"
          @click="handleAnswer"
          :disabled="!canAnswer || answered"
        >
          确定
        </el-button>
      </div>
    </div>

    <div class="practice-footer">
      <div class="progress-bar">
        <div
          v-for="(q, index) in questions"
          :key="index"
          :class="[
            'progress-item',
            {
              current: index === currentIndex,
              completed: index < currentIndex,
              correct: answers[index] && answers[index].isCorrect,
              wrong: answers[index] && !answers[index].isCorrect,
            },
          ]"
        ></div>
      </div>
    </div>

    <!-- 添加结果对话框 -->
    <el-dialog
      title="练习结果"
      :visible.sync="showResult"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="result-content">
        <div class="result-item">
          <span class="label">得分：</span>
          <span class="value">{{ practiceResult.score }}</span>
        </div>
        <div class="result-item">
          <span class="label">正确率：</span>
          <span class="value"
            >{{ (practiceResult.accuracy * 100).toFixed(1) }}%</span
          >
        </div>
        <div class="result-item">
          <span class="label">平均用时：</span>
          <span class="value">{{ practiceResult.averageTime }}秒</span>
        </div>
        <div class="result-item">
          <span class="label">题型分析：</span>
        </div>
        <div class="analysis-list" v-if="practiceResult.analysis">
          <div class="analysis-item">
            <span
              >加法：{{
                (practiceResult.analysis.addAccuracy * 100).toFixed(1)
              }}%</span
            >
          </div>
          <div class="analysis-item">
            <span
              >减法：{{
                (practiceResult.analysis.subtractAccuracy * 100).toFixed(1)
              }}%</span
            >
          </div>
          <div class="analysis-item">
            <span
              >乘法：{{
                (practiceResult.analysis.multiplyAccuracy * 100).toFixed(1)
              }}%</span
            >
          </div>
          <div class="analysis-item">
            <span
              >除法：{{
                (practiceResult.analysis.divideAccuracy * 100).toFixed(1)
              }}%</span
            >
          </div>
        </div>

        <!-- 添加趋势图 -->
        <div class="trend-chart">
          <h3>练习趋势</h3>
          <div id="trendChart" style="width: 100%; height: 300px"></div>
        </div>

        <!-- AI分析部分 -->
        <div class="ai-analysis">
          <h3>AI分析：</h3>
          <div
            v-if="aiAnalysis"
            class="analysis-content"
            style="white-space: pre-line"
          >
            {{ aiAnalysis }}
          </div>
          <div v-else class="analysis-error">
            <i class="el-icon-warning-outline"></i>
            <span>暂时无法获取AI分析</span>
          </div>
        </div>

        <div
          class="wrong-questions"
          v-if="
            practiceResult.wrongQuestions &&
            practiceResult.wrongQuestions.length > 0
          "
        >
          <h3>错题分析：</h3>
          <div class="wrong-list">
            <div
              v-for="(item, index) in practiceResult.wrongQuestions"
              :key="index"
              class="wrong-item"
            >
              <div class="question">{{ item.question }}</div>
              <div class="answers">
                <span class="user-answer">你的答案：{{ item.userAnswer }}</span>
                <span class="correct-answer"
                  >正确答案：{{ item.correctAnswer }}</span
                >
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="restartPractice">再来一次</el-button>
        <el-button @click="backToHome">返回首页</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  generateQuestions,
  submitAnswers,
  getAIAnalysis,
} from "@/api/practice";
import * as echarts from "echarts";

export default {
  name: "PracticePage",
  data() {
    return {
      difficulty: "",
      questions: [],
      currentIndex: 0,
      userAnswer: "",
      timer: 0,
      timerInterval: null,
      answers: [],
      answered: false,
      startTime: null,
      isLoading: false,
      showResult: false,
      practiceResult: {
        score: 0,
        accuracy: 0,
        averageTime: 0,
        analysis: null,
        wrongQuestions: [],
      },
      aiAnalysis: "",
      isLoadingAnalysis: false,
      trendChart: null,
    };
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentIndex] || null;
    },
    canAnswer() {
      return this.userAnswer !== "";
    },
    canSubmit() {
      return this.answers.length > 0;
    },
    isLastQuestion() {
      return this.currentIndex === this.questions.length - 1;
    },
  },
  created() {
    console.log("Practice component created");
    // 从路由获取难度等参数
    const { difficulty, count, type } = this.$route.query;
    this.difficulty = difficulty;
    this.loadQuestions(difficulty, count, type);
  },
  mounted() {
    console.log("Practice component mounted");
    this.startTimer();
    // 添加事件监听器
    this.addEventListeners();
  },
  beforeDestroy() {
    console.log("Practice component will be destroyed");
    this.stopTimer();
    // 移除事件监听器
    this.removeEventListeners();
    // 销毁图表实例
    if (this.trendChart) {
      this.trendChart.dispose();
    }
  },
  methods: {
    addEventListeners() {
      // 禁用右键菜单
      document.addEventListener("contextmenu", this.preventDefault);
      // 禁用复制
      document.addEventListener("copy", this.preventDefault);
      // 禁用粘贴
      document.addEventListener("paste", this.preventDefault);
      // 禁用剪切
      document.addEventListener("cut", this.preventDefault);
      // 禁用F12
      document.addEventListener("keydown", this.preventF12);
      // 禁用选择文本
      document.addEventListener("selectstart", this.preventDefault);
    },
    removeEventListeners() {
      document.removeEventListener("contextmenu", this.preventDefault);
      document.removeEventListener("copy", this.preventDefault);
      document.removeEventListener("paste", this.preventDefault);
      document.removeEventListener("cut", this.preventDefault);
      document.removeEventListener("keydown", this.preventF12);
      document.removeEventListener("selectstart", this.preventDefault);
    },
    preventDefault(e) {
      e.preventDefault();
      return false;
    },
    preventF12(e) {
      if (e.keyCode === 123 || (e.ctrlKey && e.shiftKey && e.keyCode === 73)) {
        e.preventDefault();
        return false;
      }
    },
    async loadQuestions(difficulty, count, type) {
      if (this.isLoading) {
        console.log("正在加载题目，请勿重复请求");
        return;
      }

      this.isLoading = true;
      const requestData = {
        difficulty,
        questionCount: parseInt(count),
        type,
      };
      console.log("准备发送请求:", requestData);

      try {
        const response = await generateQuestions(requestData);
        console.log("获取题目响应:", response);

        if (Array.isArray(response)) {
          console.log("成功获取题目:", response.length + "道");
          this.questions = response;
          this.startTime = new Date();
          this.$message.success("题目加载成功");
        } else if (response && response.code === 200) {
          if (response.data && Array.isArray(response.data)) {
            console.log("成功获取题目:", response.data.length + "道");
            this.questions = response.data;
            this.startTime = new Date();
            this.$message.success("题目加载成功");
          } else {
            console.error("题目数据格式错误:", response.data);
            this.$message.error("题目数据格式错误");
          }
        } else {
          console.error("获取题目失败:", response ? response.msg : "未知错误");
          this.$message.error(response ? response.msg : "获取题目失败");
        }
      } catch (error) {
        console.error("加载题目出错:", error);
        if (error.response) {
          console.error(
            "服务器错误:",
            error.response.status,
            error.response.data
          );
          this.$message.error(`服务器错误: ${error.response.status}`);
        } else if (error.request) {
          console.error("未收到响应，请检查服务器是否运行");
          this.$message.error("服务器无响应，请检查后端服务是否启动");
        } else {
          console.error("请求配置错误:", error.message);
          this.$message.error("请求失败，请稍后重试");
        }
      } finally {
        this.isLoading = false;
      }
    },
    startTimer() {
      this.timerInterval = setInterval(() => {
        this.timer++;
      }, 1000);
    },
    stopTimer() {
      if (this.timerInterval) {
        clearInterval(this.timerInterval);
      }
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
    },
    handleAnswer() {
      if (!this.canAnswer || this.answered) return;

      const question = this.currentQuestion;
      const timeSpent = Math.floor((new Date() - this.startTime) / 1000);

      // 记录答案
      this.answers.push({
        questionId: question.id,
        question: question.question,
        correctAnswer: question.answer,
        userAnswer: this.userAnswer,
        timeSpent: timeSpent,
        isCorrect: this.userAnswer === question.answer,
        type: question.type,
      });

      this.answered = true;

      // 延迟显示下一题或提交
      setTimeout(() => {
        if (this.isLastQuestion) {
          // 如果是最后一题，直接提交
          this.handleSubmit();
        } else {
          // 否则显示下一题
          this.nextQuestion();
        }
      }, 800); // 增加延迟时间，让用户更清楚地看到答题结果
    },
    nextQuestion() {
      this.currentIndex++;
      this.userAnswer = "";
      this.answered = false;
      this.$nextTick(() => {
        this.$refs.answerInput.focus();
      });
    },
    async handleSubmit() {
      this.isLoading = true;
      try {
        const endTime = new Date();
        const submitData = {
          userId: this.$store.state.userId,
          difficulty: this.difficulty,
          questionCount: this.questions.length,
          totalTime: this.timer,
          startTime: this.startTime,
          endTime: endTime,
          answerDetails: this.answers,
        };
        console.log("提交数据:", submitData);

        // 显示全屏加载
        const loading = this.$loading({
          lock: true,
          text: "AI正在分析你的答题情况...",
          spinner: "el-icon-loading",
          background: "rgba(255, 255, 255, 0.8)",
        });

        try {
          const response = await submitAnswers(submitData);
          console.log("服务器响应:", response);

          // 停止计时
          this.stopTimer();

          // 处理响应数据
          if (response.code === 200) {
            this.practiceResult = response.data;
            // 设置AI分析结果
            this.aiAnalysis = response.data.aiAnalysis;
            this.showResult = true;

            // 初始化趋势图
            this.$nextTick(() => {
              this.initTrendChart();
            });
          } else {
            this.$message.error(response.msg || "AI分析失败，请稍后重试");
          }
        } finally {
          // 确保无论成功失败都关闭加载动画
          loading.close();
        }
      } catch (error) {
        console.error("提交答案出错:", error);
        this.$message.error(error.message || "AI分析请求超时，请稍后重试");
      } finally {
        this.isLoading = false;
      }
    },
    viewAnalysis() {
      // 跳转到AI分析页面
      this.$router.push({
        path: "/analysis",
        query: {
          practiceId: new Date().getTime(),
          result: JSON.stringify(this.practiceResult),
        },
      });
    },
    restartPractice() {
      // 重置所有数据
      this.questions = [];
      this.currentIndex = 0;
      this.userAnswer = "";
      this.timer = 0;
      this.answers = [];
      this.answered = false;
      this.showResult = false;
      this.practiceResult = {
        score: 0,
        accuracy: 0,
        averageTime: 0,
        analysis: null,
        wrongQuestions: [],
      };

      // 重新加载题目
      const { difficulty, count, type } = this.$route.query;
      this.loadQuestions(difficulty, count, type);
      this.startTimer();
    },
    backToHome() {
      this.$router.push("/difficulty#/difficulty");
    },
    async getAIAnalysis() {
      try {
        const response = await getAIAnalysis({
          practiceRecord: {
            ...this.practiceResult,
            difficulty: this.difficulty,
            questionCount: this.questions.length,
            totalTime: this.timer,
            answerDetails: this.answers,
          },
        });

        console.log("AI分析原始响应:", response);

        // 处理响应数据
        if (!response) {
          throw new Error("未收到AI分析响应");
        }

        // 如果响应是字符串，直接使用
        if (typeof response === "string") {
          this.aiAnalysis = response;
        }
        // 如果响应包含msg字段，使用msg
        else if (response.msg) {
          this.aiAnalysis = response.msg;
        }
        // 如果响应包含data字段，使用data
        else if (response.data) {
          this.aiAnalysis = response.data;
        }
        // 其他情况
        else {
          throw new Error("无效的AI分析响应格式");
        }

        console.log("设置AI分析结果:", this.aiAnalysis);
      } catch (error) {
        console.error("获取AI分析出错:", error);
        this.aiAnalysis = "抱歉，获取AI分析时出现错误，请稍后再试。";
        throw error; // 继续抛出错误，让上层处理
      }
    },
    initTrendChart() {
      // 确保DOM元素已经渲染
      const chartDom = document.getElementById("trendChart");
      if (!chartDom) return;

      // 如果已经存在图表实例，先销毁
      if (this.trendChart) {
        this.trendChart.dispose();
      }

      // 创建新的图表实例
      this.trendChart = echarts.init(chartDom);

      // 计算每道题的准确率和用时趋势
      const accuracyData = [];
      const speedData = [];
      let correctCount = 0;

      // 修复：确保包含最后一道题
      const totalAnswers = [...this.answers];
      if (this.isLastQuestion && this.answered) {
        const lastAnswer = {
          isCorrect: this.userAnswer === this.currentQuestion.answer,
          timeSpent:
            Math.floor((new Date() - this.startTime) / 1000) -
            totalAnswers.reduce((acc, curr) => acc + curr.timeSpent, 0),
        };
        totalAnswers.push(lastAnswer);
      }

      totalAnswers.forEach((answer, index) => {
        if (answer.isCorrect) {
          correctCount++;
        }
        // 计算当前累计准确率
        accuracyData.push(((correctCount / (index + 1)) * 100).toFixed(1));
        // 计算当前题目用时（秒）
        speedData.push(answer.timeSpent);
      });

      // 配置图表选项
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        legend: {
          data: ["准确率(%)", "答题速度(秒/题)"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.answers.map((_, index) => `第${index + 1}题`),
        },
        yAxis: [
          {
            type: "value",
            name: "准确率(%)",
            min: 0,
            max: 100,
            position: "left",
            axisLine: {
              show: true,
              lineStyle: {
                color: "#5470C6",
              },
            },
            axisLabel: {
              formatter: "{value}%",
            },
          },
          {
            type: "value",
            name: "用时(秒)",
            min: 0,
            position: "right",
            axisLine: {
              show: true,
              lineStyle: {
                color: "#91CC75",
              },
            },
            axisLabel: {
              formatter: "{value}s",
            },
          },
        ],
        series: [
          {
            name: "准确率(%)",
            type: "line",
            smooth: true,
            data: accuracyData,
            itemStyle: {
              color: "#5470C6",
            },
          },
          {
            name: "答题速度(秒/题)",
            type: "line",
            smooth: true,
            yAxisIndex: 1,
            data: speedData,
            itemStyle: {
              color: "#91CC75",
            },
          },
        ],
      };

      // 设置图表配置
      this.trendChart.setOption(option);
    },
  },
  beforeRouteEnter(to, from, next) {
    console.log("Route guard: beforeRouteEnter");
    next();
  },
  beforeRouteUpdate(to, from, next) {
    console.log("Route guard: beforeRouteUpdate");
    next();
  },
};
</script>

<style scoped>
.practice-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.practice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.info {
  display: flex;
  gap: 20px;
}

.question-container {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.question {
  text-align: center;
  margin-bottom: 30px;
}

.question h2 {
  font-size: 32px;
  color: #333;
}

.answer-input {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.answer-input .el-input {
  width: 200px;
}

.progress-bar {
  display: flex;
  gap: 5px;
  margin-top: 20px;
}

.progress-item {
  flex: 1;
  height: 4px;
  background: #e0e0e0;
  border-radius: 2px;
  transition: all 0.3s;
}

.progress-item.current {
  background: #2b79ff;
}

.progress-item.completed {
  background: #909399;
}

.progress-item.correct {
  background: #67c23a;
}

.progress-item.wrong {
  background: #f56c6c;
}

.result-content {
  padding: 20px;
}

.result-item {
  margin-bottom: 15px;
  font-size: 16px;
}

.result-item .label {
  color: #606266;
  margin-right: 10px;
}

.result-item .value {
  color: #303133;
  font-weight: bold;
}

.analysis-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin: 15px 0;
}

.analysis-item {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  text-align: center;
}

.wrong-questions {
  margin-top: 20px;
}

.wrong-questions h3 {
  margin-bottom: 15px;
  color: #303133;
}

.wrong-list {
  max-height: 300px;
  overflow-y: auto;
}

.wrong-item {
  background: #fef0f0;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 10px;
}

.wrong-item .question {
  font-size: 16px;
  color: #303133;
  margin-bottom: 10px;
}

.wrong-item .answers {
  display: flex;
  justify-content: space-between;
  color: #606266;
}

.wrong-item .user-answer {
  color: #f56c6c;
}

.wrong-item .correct-answer {
  color: #67c23a;
}

.dialog-footer {
  text-align: center;
}

.ai-analysis {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.ai-analysis h3 {
  margin-bottom: 15px;
  color: #303133;
}

.analysis-loading {
  padding: 20px 0;
}

.loading-text {
  text-align: center;
  margin-top: 15px;
  color: #909399;
}

.loading-text i {
  margin-right: 8px;
}

.analysis-content {
  line-height: 1.6;
  color: #606266;
  white-space: pre-line;
  padding: 10px;
}

.analysis-error {
  text-align: center;
  padding: 30px;
  color: #909399;
}

.analysis-error i {
  font-size: 24px;
  margin-right: 8px;
  vertical-align: middle;
}

.trend-chart {
  margin: 20px 0;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.trend-chart h3 {
  margin-bottom: 15px;
  color: #303133;
}
</style>
